﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace Soft.Xml
{

    /// <summary>
    /// 拥有子节点Element
    /// </summary>
    public abstract class BaseSubElement : SoftObject
    {


        public BaseSubElement(XmlElement current)
        {
            if (current == null)
            {
                throw new ArgumentNullException("parent");
            }
            this.CurrentElement = current;
        }


        /// <summary>
        /// 当前Element节点
        /// </summary>
        public XmlElement CurrentElement { get; private set; }


        /// <summary>
        /// 获取Element
        /// </summary>
        /// <param name="subPath"></param>
        /// <param name="autoCreate"></param>
        /// <returns></returns>
        protected XmlElement GetElement(string subPath, bool autoCreate = true)
        {
            if (string.IsNullOrEmpty(subPath))
            {
                throw new ArgumentNullException("path");
            }
            XmlElement xmlElement = (XmlElement)this.CurrentElement.SelectSingleNode(subPath);
            if (xmlElement == null && autoCreate)
            {
                string[] array = subPath.Split(new char[]
                {
                    '/'
                }, StringSplitOptions.RemoveEmptyEntries);
                XmlNode xmlNode = this.CurrentElement;
                foreach (string name in array)
                {
                    xmlNode = this.GetElement(xmlNode, name, true);
                }
                xmlElement = (XmlElement)xmlNode;
            }
            return xmlElement;
        }


        /// <summary>
        /// 根据父节点 获取Element
        /// </summary>
        /// <param name="parent">父节点</param>
        /// <param name="name"></param>
        /// <param name="autoCreate">是否创建</param>
        /// <returns></returns>
        protected XmlElement GetElement(XmlNode parent, string name, bool autoCreate = true)
        {
            if (parent == null)
            {
                throw new ArgumentNullException("parent");
            }
            XmlElement xmlElement = (XmlElement)parent.SelectSingleNode(name);
            if (xmlElement == null && autoCreate)
            {
                xmlElement = this.CurrentElement.OwnerDocument.CreateElement(name);
                parent.AppendChild(xmlElement);
            }
            return xmlElement;
        }


        /// <summary>
        /// 根据Element获取对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="name"></param>
        /// <returns></returns>
        public T GetObjectElement<T>(string name) where T : BaseSubElement
        {
            return (T)((object)Activator.CreateInstance(typeof(T), new object[]
            {
                this.GetElement(this.CurrentElement, name, true)
            }));
        }



    }
}
